@extends('admin.layout.layout', ['row' => @$page])

@section('contain')

<style>
    #precutAssignNewS .modal-dialog {
        width: 750px;
        max-width: 100%;
    }

    #precutAssignNewS .modal-content {
        position: absolute;
        top: 50px;
        width: 750px;
        max-width: 100%;
    }

    #precutAssignNewS .modal-content .input-list {
        display: flex;
        flex-wrap: wrap;
    }

    #precutAssignNewS .modal-content .input-list span {
        flex: 0 0 180px;
    }
</style>

<div class="portlet">
    <div class="portlet-title">
        <div class="caption">
            <x-portlet-breadcrumb :page="$page"></x-portlet-breadcrumb>
        </div>
        <div class="actions">
            {{--@if(checkMethodsAuthority('precut_create'))
                    <div class="item">
                        <a href="/{{ request()->path() }}/create" class="btn btn-primary">{{ ts('addnew') }}</a>
        </div>
        @endif--}}
        @if (!empty($menus) && in_array('add', $menus))
        <div class="item">
            <a href="/{{ request()->path() }}/create" class="btn btn-primary">{{ ts('addnew') }}</a>
        </div>
        @endif
        @if (!empty($menus) && in_array('export', $menus))
        <div class="item">
            <a href="/{{ request()->path() }}/export" class="btn btn-warning">{{ ts('EXPORT2') }}</a>
        </div>
        @endif
        <!--<div class="item">
                    <a href="/admin/warranty/import2" class="btn btn-primary">ASP质保批量导入</a>
                </div>-->
        @if (!empty($menus) && in_array('batch_import', $menus))
        <div class="item">
            <a href="/admin/download?a=new-precut&b=template" class="btn btn-warning">ASP质保批量导入模板下载</a>
        </div>
        @endif
        @if (!empty($menus) && in_array('download_template', $menus))
        <div class="item">
            <a href="/admin/warranty/import2" class="btn btn-warning">{{ ts('DWNDR') }}</a>
        </div>
        @endif
    </div>
</div>

<div class="filter-wrapper">
    <form action="/{{ request()->path() }}/" class="form-inline filter-form">
        <div class=" input-group mb-3 custom-control-inline">
            <input type="text" class="form-control s-input" name="value" value="{{ request()->input('value') }}" placeholder="请输入专车专用套件ID/膜卷号/店面名称/质保ID" style="width: 480px;">
        </div>
        <div class="input-group mb-3 custom-control-inline">
            <select name="status" class="form-control">
                <option value="">{{ ts('select').' '.ts('status') }}</option>
                <option value="1" {{ request()->input('status') == 1 ? 'selected' : '' }}>{{ ts('stai1') }}</option>
                <option value="0" {{ request()->input('status')!==null && request()->input('status') == 0 ? 'selected' : '' }}>{{ ts('stai0') }}</option>
                <option value="2" {{ request()->input('status') == 2 ? 'selected' : '' }}>{{ ts('dfp') }}</option>
            </select>
        </div>
        <x-flatpickr-date-range label="{{ ts('createdat') }}"></x-flatpickr-date-range>
        <div class="mb-3">
            <button class="btn btn-primary">{{ ts('SEARCH') }}</button>
            <a href="/{{ request()->path() }}/" class="btn btn-warning">{{ ts('RESET') }}</a>
        </div>

    </form>
</div>

<div>
    <table class="table text-nowrap bt-table d-none data-list">
        <thead>
            <tr class="order_column">
                <th></th>
                <th>{{ ts('sequence') }}</th>
                <th>{{ ts('PRECUTID') }}</th>
                <th>{{ ts('azbw') }}</th>
                <th>{{ ts('ylcd2') }}</th>
                <th>{{ ts('rollnumber') }}</th>
                <th>{{ ts('JXSMC') }}</th>
                <th>{{ ts('CREATEDAT') }}</th>
                <th>{{ ts('status') }}</th>
                <th>{{ ts('OPERATIONS') }}</th>
            </tr>
        </thead>
        <tbody>
            @foreach($data as $k => $v)
            @php
            $pvcs = explode("\n", @$v->roll_numbers) ?: [];
            @endphp
            @if(session('hightlight') && session('hightlight.type')=='precut' && session('hightlight.id')==$v->id)
            <tr class="item-list table-warning">
                @else
            <tr class="item-list">
                @endif
                <td class="text-center primary-id">
                    <input type="checkbox" class="warranty_icheck icheck_input" name="ids[]" value="{{ $v->id }}">
                </td>
                <td class="text-center">
                    {{ @$data->firstItem()+$k }}
                </td>
                <td class="precut-id">
                    {{ @$v->precut_id }}
                </td>
                <td>
                    {{ ts('new_precut_part.'.@$v->part_id) }}
                </td>
                <td>
                    {{ @$v->length }} cm
                </td>
                <td>
                    @foreach($pvcs as $vc)
                    <div>{{ $vc }}</div>
                    @endforeach
                </td>
                <td>
                    {{ getJc(@$v->user_id) }}
                </td>
                <td>
                    {{ fdate2($v->created_at) }}
                </td>
                <td>
                    @if(empty(@$v->user_id))
                    {{ ts('DFP') }}
                    @else
                    {{ ts('STAI'.@$v->status) }}
                    @endif
                </td>
                <td>
                    @if($v->status != 1)
                    <button type="button" class="btn btn-primary btn-sm" onclick="oNAP('{{ $v->id }}', '{{ $v->precut_id }}', '{{ @$v->user_id }}')">{{ ts('ASSIGN') }}</button>
                    @else
                    <button type="button" disabled class="btn btn-secondary btn-sm">{{ ts('ASSIGN') }}</button>
                    @endif

                    <a class="btn btn-success btn-sm" href='/{{ request()->path() }}/{{ @$v->id }}'>{{ ts('VIEW') }}</a>

                    @if(@$v->status == 0 && @$v->user_id == 0)
                    <span class="btn btn-danger btn-sm" onclick="handleDelete({{ @$v->id }})">{{ ts('delete') }}</span>
                    @endif
                </td>
            </tr>
            @endforeach
        </tbody>
    </table>

    <div class="row my-3">
        <div class="col-auto">
            <label style="cursor: pointer"><input type="checkbox" class="icheck_all" data-ele=".warranty_icheck"><span class="ml-2">{{ ts('SELECTALL') }}</span></label>
            <span class="btn btn-primary ml-3" onclick="deleteAlliCheck('.warranty_icheck', '/admin/new-precut/deletes')">{{ ts('delete') }}</span>
            <span class="btn btn-primary ml-3" onclick="oNAPS('.warranty_icheck')">批量分配</span>
        </div>
        <div class="col">
            {{ $data->appends(request()->input())->links() }}
        </div>
    </div>
</div>

<form class="modal fade modal-s1" id="precutAssignNew">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title font-green">{{ ts('ASSIGN') }}</h5>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body">
                <div class="form-item">
                    <div class="form-label" required="">{{ ts('PRECUTID') }}</div>
                    <div class="form-input">
                        <input type="text" hidden name="id" class="form-control">
                        <input type="text" readonly name="precut_id" class="form-control">
                    </div>
                </div>

                <div class="form-item">
                    <div class="form-label" required="">{{ ts('distributor') }}</div>
                    <div class="form-input">
                        <select class="form-control sdid" name="sdid">
                            @foreach(gDV1() as $v)
                            <option value="{{ @$v->id }}">{{ @$v->abbr ?: @$v->company_name }}</option>
                            @endforeach
                        </select>
                    </div>
                </div>
                <div class="form-item">
                    <div class="form-label" required="">{{ ts('assigntouser') }}</div>
                    <div class="form-input">
                        <select class="form-control user_id" name="user_id"></select>
                    </div>
                </div>

                <div class="py-3 text-center">
                    <button type="button" class="btn btn-primary" onclick="handleAssign(this)">{{ ts('assign') }}</button>
                </div>
            </div>
        </div>
    </div>
</form>

<form class="modal fade modal-s1" id="precutAssignNewS">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title font-green">{{ ts('ASSIGN') }}</h5>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body">
                <input type="text" hidden name="id" class="form-control">

                <div class="form-item">
                    <div class="form-label" required="">{{ ts('PRECUTID') }}</div>
                    <div class="form-input input-list">
                        <input type="text" readonly class="form-control">
                    </div>
                </div>

                <div class="form-item">
                    <div class="form-label" required="">{{ ts('distributor') }}</div>
                    <div class="form-input">
                        <select class="form-control sdid" name="sdid" style="width: 100%;">
                            @foreach(gDV1() as $v)
                            <option value="{{ @$v->id }}">{{ @$v->abbr ?: @$v->company_name }}</option>
                            @endforeach
                        </select>
                    </div>
                </div>
                <div class="form-item">
                    <div class="form-label" required="">{{ ts('assigntouser') }}</div>
                    <div class="form-input">
                        <select class="form-control user_id" name="user_id" style="width: 100%;"></select>
                    </div>
                </div>

                <div class="py-3 text-center">
                    <button type="button" class="btn btn-primary" onclick="handleAssignS(this)">{{ ts('assign') }}</button>
                </div>
            </div>
        </div>
    </div>
</form>
</div>


@endsection



@section('script')
<script>
    $(function() {
        $(".sdid, .user_id").select2();
    });

    function exportData() {
        let url = '/admin/new-precut/export';
        let key = $("[name='value']").val();
        let status = $("[name='status']").val();
        let startDate = $("[name='startdate']").val();
        let endDate = $("[name='enddate']").val();
        url += "?key=" + key + "&status=" + status + "&startDate=" + startDate + "&endDate=" + endDate;
        window.location.href = url;
    }

    $('body').on('change', '[name="sdid"]', function() {
        var val = $(this).val();
        var $that = $(this);
        if (!val) {
            $('.portlet select[name="user_id"]').empty().append(makeSelectOptionsOnly([]))
        }
        request.get('/admin/ajax/getUsers', {
                params: {
                    t: 'd',
                    user_id: val
                }
            })
            .then(function(d) {
                var data = d.data
                $('.portlet select[name="user_id"]').empty().append(makeSelectOptionsOnly(data))
            })
            .catch(function(d) {
                toastr.error(d.msg)
            })
    })
    $(document).ready(function() {
        if ($('[name="sdid"]').length >= 1) {
            request.get('/admin/ajax/getUsers', {
                    params: {
                        t: 'd',
                        user_id: $('[name="sdid"]').val()
                    }
                })
                .then(function(d) {
                    var data = d.data
                    $('.portlet select[name="user_id"]').empty().append(makeSelectOptionsOnly(data))
                })
                .catch(function(d) {
                    toastr.error(d.msg)
                })
        }

        $('.table.bt-table').bootstrapTable({
            fixedColumns: true,
            fixedNumber: 1,
            fixedRightNumber: 1,
        }).removeClass('d-none')
    });

    function oNAP(id, precut_id, user_id) {
        $('#precutAssignNew')[0].reset();
        $('#precutAssignNew').find('[name="id"]').val(id)
        $('#precutAssignNew').find('[name="precut_id"]').val(precut_id)
        $('#precutAssignNew [name="user_id"]').val(user_id);
        $('#precutAssignNew [name="sdid"]').trigger('change');
        $('#precutAssignNew').modal();
    }
    var MultiAssignForm = {};

    function oNAPS(ele) {
        var ids = [];
        for (var i = $(ele).length - 1; i >= 0; i--) {
            var item = $(ele).eq(i);
            if (item.is(':checked')) {
                ids.push(item.val())
            }
        }
        if (ids.length < 1) {
            alert('至少选择一个！')
            return false
        }
        console.log(ids)

        var trs = $('.table.data-list tr');
        var precutIdList = [];
        for (var i = 0; i < trs.length; i++) {
            var tr = trs.eq(i);
            var idVal = tr.find('[name="ids[]"]').val();
            var precutId = tr.find('td.precut-id').text();
            if (ids.indexOf(idVal) >= 0 || ids.indexOf(String(idVal)) >= 0) {
                precutIdList.push(precutId)
            }
        }
        console.log(precutIdList);
        var str = '';
        for (var i = 0; i < precutIdList.length; i++) {
            str += '<span><input type="text" readonly class="form-control" value="' + precutIdList[i] + '"></span>';
        }
        $('#precutAssignNewS .input-list').empty().append(str);

        $('#precutAssignNewS')[0].reset();
        $('#precutAssignNewS').find('[name="id"]').val(ids.join(','));
        $('#precutAssignNewS [name="sdid"]').trigger('change');
        $('#precutAssignNewS').modal();
    }

    function handleAssignS(dom) {
        $(dom).attr('disabled', true);
        var form = formObjV2('#precutAssignNewS');
        var state = false;
        var msg;
        console.log('form', form)
        if (!form['id'] && !msg) {
            msg = '套件ID 不能为空';
        }
        /*if (!form['sdid'] && !msg) {
            msg = '套件ID 不能为空';
        }*/
        if (!form['user_id'] && !msg) {
            msg = '分配用户 不能为空';
        }
        if (msg) {
            alert(msg);
            $(dom).attr('disabled', false);
            return false;
        }
        console.log(form['id']);
        form['id'] = form['id'].split(',');
        var url = '/admin/ajax/newPrecut';
        var params = {
            t: 'assigns',
        };
        form = Object.assign({}, form, params);
        request.post(url, form)
            .then(function(d) {
                sweetAlert('', '分配成功！', 'success')
                    .then(function(d) {
                        window.location.reload()
                    })
            })
            .catch(function(d) {
                sweetAlert('', d.msg || '分配失败，请刷新页面重新尝试！', 'error')
                $(dom).attr('disabled', false);
            })
    }

    function handleAssign(dom) {
        $(dom).attr('disabled', true);
        var form = formObjV2('#precutAssignNew');
        var state = false;
        var msg;
        if (!form['id'] && !msg) {
            msg = '套件ID 不能为空';
        }
        if (!form['precut_id'] && !msg) {
            msg = '专车专用套件ID 不能为空';
        }
        /*if (!form['sdid'] && !msg) {
            msg = '套件ID 不能为空';
        }*/
        if (!form['user_id'] && !msg) {
            msg = '分配用户 不能为空';
        }
        if (msg) {
            alert(msg);
            $(dom).attr('disabled', false);
            return false;
        }
        var url = '/admin/ajax/newPrecut';
        var params = {
            t: 'assign',
        };
        form = Object.assign({}, form, params);
        request.post(url, form)
            .then(function(d) {
                sweetAlert('', '分配成功！', 'success')
                    .then(function(d) {
                        window.location.reload()
                    })
            })
            .catch(function(d) {
                sweetAlert('', d.msg || '分配失败，请刷新页面重新尝试！', 'error')
                $(dom).attr('disabled', false);
            })
    }
</script>
@endsection